import router from '@/router';
import { RouteRecordRaw } from 'vue-router';
import { formatFlatteningRoutes, formatTwoStageRoutes } from './formatRoutes';
import { dynamicRoutes } from '@/router/routes';

/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes（@/router/route）第一个顶级 children 的路由一维数组，非多级嵌套
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 */
export function setAddRoute() {
	setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
		const routeName = route.name;
		if (routeName && !router.hasRoute(routeName)) router.addRoute(route);
	});
}

/**
 * 定义404界面
 * @link 参考：https://next.router.vuejs.org/zh/guide/essentials/history-mode.html#netlify
 */
const pathMatch = {
	path: '/:pathMatch(.*)',
	redirect: '/404',
};

/**
 * 获取有当前用户权限标识的路由数组，进行对原路由的替换
 * @description 替换 dynamicRoutes（@/router/route）第一个顶级 children 的路由
 * @returns 返回替换后的路由数组
 */
export function setFilterRouteEnd() {
	const filterRouteEnd = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
	if (!filterRouteEnd) return [];
	filterRouteEnd[0].children = [...setFilterRoute(filterRouteEnd[0].children!), { ...pathMatch }];
	return filterRouteEnd;
}

/**
 * 获取当前用户权限标识去比对路由表（未处理成多级嵌套路由）
 * @description 这里主要用于动态路由的添加，router.addRoute
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 * @param chil dynamicRoutes（@/router/route）第一个顶级 children 的下路由集合
 * @returns 返回有当前用户权限标识的路由数组
 */
export function setFilterRoute(chil: Array<RouteRecordRaw>) {
	let filterRoute: Array<RouteRecordRaw> = [];
	chil.forEach((route: RouteRecordRaw) => {
		const metaAuth = route.meta?.auth as Array<string> | undefined;
		if (metaAuth) {
			metaAuth.forEach((metaAuth: string) => {
				['admin'].forEach((auth: string) => {
					if (metaAuth === auth) filterRoute.push({ ...route });
				});
			});
		}
	});
	return filterRoute;
}